<?php
class Pay_Pay{

    public $params = array();
    public $util = NULL;

    public function __construct($order_data){

        $notify_url = Arr::get($order_data, 'notify_url');
        $notify_url = empty($notify_url) ?  Util_Common::trimString(Kohana::config("config.info.notify_url")) : $notify_url;

        $this->params['appid'] = Util_Common::trimString(Kohana::config("config.info.appid"));
        $this->params['mch_id'] = Util_Common::trimString(Kohana::config("config.info.mchid"));
        $this->params['device_info'] = Util_Common::trimString("WEB");
        $this->util = new Util_Common();
        $this->params['nonce_str'] = Util_Common::trimString($this->util->create_noncestr());
        $this->params['body'] = Util_Common::trimString($order_data['body']);
        $this->params['out_trade_no'] = Util_Common::trimString($order_data['out_trade_no']);
        $this->params['total_fee'] = Util_Common::trimString($order_data['total_fee']);
        $this->params['spbill_create_ip'] = Util_Common::trimString("127.0.0.1");
        $this->params['trade_type'] = Util_Common::trimString("NATIVE");
        $this->params['notify_url'] = $notify_url;

    }

    public function create_pay_order(){
        $sign = $this->get_sign();
        $this->params['sign'] = $sign;
        $xml = $this->util->arrayToXml($this->params);
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $responseXml = $this->curl_post_ssl($url,$xml);
        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
//        echo url::site("/payment/weixin/notify", 'http', FALSE);
        $qrCodeImgSrc = "";
        if($responseObj->return_code == "SUCCESS" && $responseObj->code_url != ""){
            $qrCodeImgSrc = "http://paysdk.weixin.qq.com/example/qrcode.php?data=".urlencode($responseObj->code_url);
        }

//        echo "<img src='$qrCodeImgSrc'>";
//        var_dump($this->params);
//输出图片
//            imagepng($QR, '/tmp/helloweixin.png');
//            echo '<img src="E:/tmp/qrcode.png">';

//        var_dump($responseObj);
        return $qrCodeImgSrc;
//        file_put_contents("request.xml",$xml);
//        file_put_contents("responseXml.xml",$responseXml);

    }

    public function check_sign_parameters(){
        if(
            $this->params['appid'] == null ||
            $this->params['mch_id'] == null ||
            $this->params['device_info'] == null ||
            $this->params['nonce_str'] == null ||
            $this->params['body'] == null ||
            $this->params['out_trade_no'] == null ||
            $this->params['total_fee'] == null ||
            $this->params['spbill_create_ip'] == null ||
            $this->params['trade_type'] == null ||
            $this->params['notify_url'] == null
        ){
            return false;
        }
        return true;
    }

    protected function get_sign(){
        try {
            $partnerkey = Kohana::config("config.info.partnerkey");
            if (null == $partnerkey || "" == $partnerkey ) {
                throw new Exception("密钥不能为空！" . "<br>");
            }
            if($this->check_sign_parameters() == false) {   //检查生成签名参数
                throw new Exception("生成签名参数缺失！" . "<br>");
            }
            $commonUtil = new Util_Common();
            ksort($this->params);
            $unSignParaString = $commonUtil->formatQueryParaMap($this->params, false);

            return $commonUtil->sign($unSignParaString,$commonUtil->trimString($partnerkey));
        }catch (Exception $e)
        {
            die($e);
        }
    }

    function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种
        //第一种方法，cert 与 key 分别属于两个.pem文件
//        curl_setopt($ch,CURLOPT_SSLCERT,'/resource/qr_pay/apiclient_cert.pem');
//        curl_setopt($ch,CURLOPT_SSLKEY,'/resource/qr_pay/apiclient_key.pem');
//        curl_setopt($ch,CURLOPT_CAINFO,'/resource/qr_pay/rootca.pem');

        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

}
